package com.typingtutor.ui;

import com.typingtutor.ui.compose.ButtonTabComponent;
import com.typingtutor.ui.tabs.DocumentTab;
import com.typingtutor.ui.tabs.StatisticsChartTab;
import com.typingtutor.ui.tabs.TypingPracticeTab;
import lombok.Getter;

import javax.swing.*;
import java.awt.*;
import java.net.URL;

public class TypingTutor extends JFrame {
    private static JTabbedPane tabbedPane;
    private DocumentTab documentTab;
    private final static String LOGO = "img/logo/logo.png";

    public TypingTutor() {
        setTitle("打字通软件");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        // 设置窗口图标
        setIconImage(getIcon(LOGO));

        // 适配 macOS 的 Dock 栏图标
        setupMacDockIcon(LOGO);

        tabbedPane = new JTabbedPane();

        documentTab = new DocumentTab(this);
        // 添加标签页并设置自定义标签
        addTab("词典", documentTab.getPanel());
        // 添加 ChangeListener 监听选项卡切换事件
        tabbedPane.addChangeListener((e) -> {
            StatisticsChartTab statisticsChartTab = TypingPracticeTab.getStatisticsChartTab();
            if (statisticsChartTab != null) {
                statisticsChartTab.loadDataFromDatabase();
            }
        });
        // 将 JTabbedPane 添加到窗口中心
        add(tabbedPane, BorderLayout.CENTER);
        setLocationRelativeTo(null);
        setVisible(true);
    }


    // 添加标签页并设置自定义标签的方法
    public static void addTab(String title, Component component) {
        // 将组件添加到 JTabbedPane
        tabbedPane.addTab(title, component);
        // 获取当前标签页的索引
        int index = tabbedPane.indexOfComponent(component);
        // 设置自定义标签
        tabbedPane.setTabComponentAt(index, new ButtonTabComponent(tabbedPane));
        // 将 JTabbedPane 的当前选中索引设置为新添加的标签页的索引
        tabbedPane.setSelectedIndex(index);
    }

    private Image getIcon(String path) {
        URL resource = getClass().getClassLoader().getResource(path);
        if (resource != null) {
            return Toolkit.getDefaultToolkit().getImage(resource);
        }
        return null;
    }

    private void setupMacDockIcon(String logo) {
        String osName = System.getProperty("os.name").toLowerCase();
        if (osName.contains("mac")) {
            try {
                Class<?> applicationClass = Class.forName("com.apple.eawt.Application");
                Object application = applicationClass.getMethod("getApplication").invoke(null);
                Image icon = Toolkit.getDefaultToolkit().getImage(getClass().getClassLoader().getResource(logo));
                applicationClass.getMethod("setDockIconImage", Image.class).invoke(application, icon);
            } catch (Exception e) {
                System.err.println("设置 macOS Dock 图标时出错: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }

}